<template>
    <div>
        <!-- 面包屑导航 -->
        <el-breadcrumb separator="/">
            <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
            <el-breadcrumb-item>用户管理</el-breadcrumb-item>
            <el-breadcrumb-item>用户列表</el-breadcrumb-item>
        </el-breadcrumb>     
        
          <!-- 卡片 -->
        <el-card align="left">
            <!-- 搜索框 -->
            <el-row :gutter="20">
                <el-col :span="6">
                    <el-input placeholder="请输入内容" v-model="queryInfo.query" class="input-with-select" clearable @clear="handleSearchVal()">
                        <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
                    </el-input>
                </el-col>
                <el-col :span="6">
                     <el-button type="primary" @click="addUserVisible=!addUserVisible">添加用户</el-button>
                </el-col>
            </el-row>

            <!-- 表格 -->
              <el-table
                :data="userList"
                border
                style="width: 100%">
                <el-table-column
                type="index">
                </el-table-column>
                <el-table-column
                prop="username"
                label="姓名">
                </el-table-column>
                <el-table-column
                prop="email"
                label="邮箱">
                </el-table-column>
                <el-table-column
                prop="mobile"
                label="电话">
                </el-table-column>
                <el-table-column
                prop="role_name"
                label="角色">
                </el-table-column>
                <el-table-column
                prop="mg_state"
                label="状态"
                >
                    <template slot-scope="scope">
                        <el-switch 
                        @change="handleChangeState(scope.row.id,$event)"
                        v-model="scope.row.mg_state">
                        </el-switch>
                    </template>
                </el-table-column>
                <el-table-column
                label="操作"
                fixed="right"
                width="230"
                >
                    <template slot-scope="scope">
                        <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
                            <el-button type="primary" icon="el-icon-edit" @click="handleEdit(scope.$index, scope.row)">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="删除" placement="top">
                            <el-button type="danger" icon="el-icon-delete" @click="handleDelete(scope.$index, scope.row)">
                            </el-button>
                        </el-tooltip>
                        <el-tooltip class="item" effect="dark" content="设置" placement="top-end">
                            <el-button type="warning" icon="el-icon-setting" @click="handlesetting(scope.$index, scope.row)">
                            </el-button>
                        </el-tooltip>
                    </template>
                </el-table-column>
             </el-table>
             <el-pagination
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="queryInfo.pagenum"
                :page-sizes="[1, 2, 3, 4]"
                :page-size="queryInfo.pagesize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total">
            </el-pagination>
        </el-card>

        <!-- 添加用户dialog对话框 -->
        <el-dialog
        title="修改用户"
        :visible.sync="addUserVisible"
        width="50%"
        align="left"
        @close="handleClose('addUserFormRef')"
        >

        <!-- 内容区域 -->
            <el-form :model="addUserForm" :rules="addUserFormRul" ref="addUserFormRef" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="addUserForm.username"></el-input>
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="addUserForm.password" type="password"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="addUserForm.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="addUserForm.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addUserVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleAddUser">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 修改内容区域 -->
        <el-dialog
        title="编辑用户"
        :visible.sync="editUserVisible"
        width="50%"
        align="left"
        >

            <!-- 内容区域 -->
            <el-form :model="editUserParams" :rules="editUserParamsRul" ref="editUserParamsRef" label-width="100px" class="demo-ruleForm">
                <el-form-item label="用户名">
                    <!-- 不可点击 -->
                    <el-input v-model="editUserParams.username" disabled></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="editUserParams.email"></el-input>
                </el-form-item>
                <el-form-item label="手机" prop="mobile">
                    <el-input v-model="editUserParams.mobile"></el-input>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="editUserVisible = false">取 消</el-button>
                <el-button type="primary" @click="handleEditUserList">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
export default {
    data(){
        //验证邮箱的规则
        var checkEmail = (rule, value, cb) => {
            const regEmail = /^\w+@\w+(\.\w+)+$/
            if (regEmail.test(value)) {
            return cb()
            }
            //返回一个错误提示
            cb(new Error('请输入合法的邮箱'))
        }
        //验证手机号码的规则
        var checkMobile = (rule, value, cb) => {
            const regMobile = /^1[345789]\d{9}$/
            if (regMobile.test(value)) {
                return cb()
            }
            //返回一个错误提示
            cb(new Error('请输入合法的手机号码'))
        }
        return {
          input3: '',
          queryInfo:{
            query: '',
            pagenum: 1 ,
            pagesize: 2
          },
            //   用户列表
          userList: [],
          total: 0,
          addUserVisible: false,
          editUserVisible: false,
            //   添加用户参数
          addUserForm: {
              username: '',
              password: '',
              email: '',
              mobile: ''
          },
             //   校验规则
           addUserFormRul: {
                username: [
                    { required: true, message: '请输入用户名', trigger: 'blur' },
                    { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
                ],
                password: [
                    { required: true, message: '请输入密码', trigger: 'blur' },
                    { min: 3, max: 6, message: '长度在 3 到 6 个字符', trigger: 'blur' }
                ],
                email: [
                    { validator: checkEmail,  trigger: 'blur' }
                ],
                mobile: [
                    { validator: checkMobile,  trigger: 'blur' }
                ]
            },
            //  存储获取到的用户信息
            editUserParams:{
                id: "",
                mobile: "",
                username: "",
                email: ""
            },
            //  修改用户信息对话框规则
            editUserParamsRul:{
                email: [
                    { validator: checkEmail,  trigger: 'blur' }
                ],
                mobile: [
                    { validator: checkMobile,  trigger: 'blur' }
                ]
            },
            
        }
    },
    created(){
        this.getUserList()
    },
    methods:{
        // 将表单清空
        handleClose(done) {
            this.$refs[done].resetFields();
        },
        //清空,触发用户列表的请求 
        handleSearchVal() {
            this.getUserList()
        },
        //请求用户列表数据
        async getUserList() {
            let {data:res} = await this.$http.get('users',{params:this.queryInfo})
            if(res.meta.status!==200){
                this.$message.error("获取管理员列表失败")
                return
            }
            this.$message.success("获取管理员列表成功")
            this.userList = res.data.users;
            this.total = res.data.total;
        },
        // 获取编辑信息
        async handleEdit(index, row) {
            // console.log(index, row);
            // 存储获取到的用户id
            let {data:res} = await this.$http.get(`users/${row.id}`);
            if(res.meta.status!==200){
                this.$message.error(res.meta.msg)
            }
            // 复制对象方法1
            // this.editUserParams = res.data;
            // let {id,mobile,rid,username,email} = res.data;
            // this.editUserParams = {id,mobile,rid,username,email}
            // 复制对象方法2
             Object.keys(this.editUserParams).forEach(key=>{this.editUserParams[key]=res.data[key]})
            //  让页面显示
             this.editUserVisible = !this.editUserVisible;
        },
        // 点击确定编辑用户按钮,发送给后台
        async handleEditUserList(){
            let {data:res} = await this.$http.put(`users/${this.editUserParams.id}`,this.editUserParams)
            if(res.meta.status!==200){
                this.$message.error(res.meta.msg)
                return
            }
            this.$message.success(res.meta.msg)
            // 更新列表
            this.getUserList();
            this.editUserVisible = false;
        },
        handleDelete(index, row) {
            console.log(index, row);
            this.$confirm('此操作将永久删除该用户, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
            }).then(async () => {
                // 点击确定,发起后台请求,删除该用户
                let {data:res} = await this.$http.delete(`users/${row.id}`)
                if(res.meta.status!==200){
                    this.$message({
                        type: 'error',
                        message: '删除失败'
                    })
                    return
                }
                this.$message({
                    type: 'success',
                    message: '删除成功!'
                });
                this.isLastPage()
                this.getUserList()
            }).catch(() => {
                this.$message({
                    type: 'info',
                    message: '已取消删除'
                });            
            });
        },
        handlesetting(index, row){
            console.log(index, row);
        },
        handleSizeChange(val) {
            console.log(`每页 ${val} 条`);
            this.queryInfo.pagesize = val;
            this.getUserList();
        },
        handleCurrentChange(val) {
            console.log(`当前页: ${val}`);
            this.queryInfo.pagenum = val;
            this.getUserList();
        },
        async handleChangeState(id,status) {
            // 当前switch的状态
            // alert(status)
            let {data:res} = await this.$http.put(`users/${id}/state/${status}`);
            // 如果失败了
            if(res.meta.status!==200){
                this.$message.error("修改失败")
                // 因为前端不管有没有请求成功,都会改变,为了避免与后台数据不一致就需要重新请求后台数据
                this.getUserList();
                return
            }
            this.$message.success("修改成功")
        },
        //  添加用户
        handleAddUser(){
            this.$refs.addUserFormRef.validate(async valid=>{
                if(!valid) return this.$message.error("请输入正确的校验规则")
                this.addUserVisible = false;
                let {data:res} = await this.$http.post('users',this.addUserForm);
                if(res.meta.status!==201){
                    this.$message.error(res.meta.msg)
                    return
                }
                this.$message.success("添加用户成功")
            })
        },
        // 使用Element分页组件删除最后一页的最后一条数据后，currentPage显示正确，数据没显示的问题
        isLastPage () {
            // 根据总的数据条数total和一页显示的数据条数，得到总页数
            let lastPage = Math.ceil(this.total / this.queryInfo.pagesize)
            // 判断当前页是否是最后一页
            if (this.queryInfo.pagenum === lastPage) {
                this.queryInfo.pagenum--
            }
        }
    }
}
</script>

<style>

</style>